﻿using System;
using Microsoft.Practices.Unity;
using UnityDemo.LoggingUtility;

namespace UnityDemo.DemoCode
{
    /// <summary>
    /// This Demo shows how to pass a constructor parameter to a class
    /// </summary>
    public class ConstructionInjectionMemberDemo : IDemo
    {
        public ConstructionInjectionMemberDemo()
        {
            InjectionConstructorDemo();
            NamedInjectionDemo();
        }

        private void InjectionConstructorDemo()
        {
            var uri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");

            var container = UnityProvider.UnityInstanceProvider.NewUnityInstance;
            container.RegisterType<IServiceProvider, ServiceProvider>(new InjectionConstructor(uri));
            var provider = container.Resolve<IServiceProvider>();
            LogerInstance.Logger.Write(provider);
        }

        private void Exp()
        {
            var uri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");

            var container = UnityProvider.UnityInstanceProvider.NewUnityInstance;
            container.RegisterType<IServiceProvider, ServiceProvider>(new InjectionConstructor(uri));
            var provider = container.Resolve<IServiceProvider>();
            LogerInstance.Logger.Write(provider);
        }

        private void ExplicitDemo()
        {
            var uri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");

            var container = UnityProvider.UnityInstanceProvider.NewUnityInstance;
            container.RegisterType<IServiceProvider, ServiceProvider>(new InjectionConstructor(uri));
            var provider = container.Resolve<IServiceProvider>();
            LogerInstance.Logger.Write(provider);
        }

        private void NamedInjectionDemo()
        {
            try
            {
                var uri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");
                const string instanceName = "NamedInstance";
                var container = UnityProvider.UnityInstanceProvider.NewUnityInstance;
                container.RegisterType<IServiceProvider, ServiceProvider>(instanceName, new InjectionConstructor(uri));
                container.RegisterType<IServiceProvider, ServiceProvider>();

                var provider = container.Resolve<IServiceProvider>();
                LogerInstance.Logger.Write(provider);
                provider = container.Resolve<IServiceProvider>(instanceName);
                LogerInstance.Logger.Write(provider);
            }
            catch (Exception)
            {
                LogerInstance.Logger.ExceptionMessage("This demo is to show an known bug in resolving a named type in using Injection contructor");
            }
        }
    }
}